package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public String findUserByUp(User user) {
        /*将明文密码加密*/
        String md5Pass = DigestUtils
                .md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        /*以user为查询条件进行查询 查询数据库有没有这样一条数据*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User userDB = userMapper.selectOne(queryWrapper);
        String token = UUID.randomUUID().toString().replace("-", "");
        /*如果查询到这条数据 则返回token 如果userDB==null则返回null*/
        return userDB==null?null:token;
    }

    @Override
    public PageResult findUserByPage(PageResult pageResult) {
        //1.定义分页对象  2个参数
        IPage<User> page =
                new Page<>(pageResult.getPageNum(),
                        pageResult.getPageSize());
        //2.定义查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //3.判断用户是否有参数
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"username", pageResult.getQuery());

        //page 参数4个
        page = userMapper.selectPage(page,queryWrapper);
        //4.获取总记录数
        long total = page.getTotal();
        //5.获取分页后的结果
        List<User> userList = page.getRecords();
        return pageResult.setTotal(total).setRows(userList);
    }

    @Override
    public void updateStatus(User user) {   //id/status
        userMapper.updateById(user);
    }

    @Override
    public void addUser(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass).setStatus(true);
        userMapper.insert(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteById(id);
    }
}
